/*
 * @Description: Validate for post body
 * @Author: Jinzhu Liu
 * @Date: 2021-12-18 22:44:00
 * @LastEditor: Jinzhu Liu
 * @LastEditTime: 2021-12-26 23:43:00
 */

import Schema, { Rules, Values } from "async-validator";
import { Context } from "koa";

/**
 * @description: Validation tool method
 * @param {Context} ctx Http Context
 * @param {Rules} rules Validation rules
 * @param {boolean} fullErrorFlag Whether complete error messages are returned
 * @return {*}
 */
async function validate<T extends Values>(
    ctx: Context, 
    rules: Rules,
    fullErrorFlag: boolean = false): Promise<{ data: T|null, error: any|null }> {
    
    const validator = new Schema(rules)
    let data: any = {}

    switch (ctx.method) {
        case "GET":
            break
        case "POST":
            data = getFormData(ctx)
            break
        case "PUT":
            data = getFormData(ctx)
        case "DELETE":
            break
    }

    return await validator.validate(data).then(() => {
        return {
            data: data as T,
            error: null
        }
    }).catch(err => {
        if (fullErrorFlag) {
            return {
                error: err,
                data: null
            }
        }
        return {
            error: err.errors[0].message,
            data: null
        }
    })
}

function getFormData(ctx: Context) {
    return ctx.request.body
}

export default validate